﻿using System;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;

namespace shubiao
{
    public partial class MainWindow : Window
    {
        [DllImport("user32.dll")]
        public static extern bool GetCursorPos(out POINT lpPoint);

        public struct POINT
        {
            public int X;
            public int Y;
        }

        private CancellationTokenSource _cancellationTokenSource;

        public MainWindow()
        {
            InitializeComponent();
            StartUpdatingMousePosition();
        }

        private void StartUpdatingMousePosition()
        {
            _cancellationTokenSource = new CancellationTokenSource();
            var token = _cancellationTokenSource.Token;

            Task.Run(async () =>
            {
                while (!token.IsCancellationRequested)
                {
                    await Dispatcher.InvokeAsync(UpdateMousePosition);
                    await Task.Delay(1000, token); // 每秒更新一次
                }
            }, token);
        }

        private void UpdateMousePosition()
        {
            if (GetCursorPos(out POINT point))
            {
                MousePositionText.Text = $"鼠标位置: X = {point.X}, Y = {point.Y}";
            }
        }

        protected override void OnClosed(EventArgs e)
        {
            _cancellationTokenSource.Cancel();
            _cancellationTokenSource.Dispose();
            base.OnClosed(e);
        }
    }
}
